<template>
  <PageContainer>
    <div class="compose-page">
      <div class="compose-header">
        <h1 class="page-title">图文组合</h1>
        <p class="page-description">选择模板，编辑内容，创建精美的图文作品</p>
      </div>
      
      <div class="compose-content">
        <!-- 左侧：模板选择和内容编辑 -->
        <div class="compose-sidebar">
          <!-- 模板选择器 -->
          <TemplateSelector
            :selected-template="selectedTemplate"
            @select-template="handleSelectTemplate"
            @create-template="handleCreateTemplate"
          />
          
          <!-- 内容编辑器 -->
          <ContentEditor
            v-if="selectedTemplate"
            :selected-image="selectedImage ?? undefined"
            :available-images="availableImages"
            :template="selectedTemplate"
            @image-change="handleImageChange"
            @text-change="handleTextChange"
            @style-change="handleStyleChange"
            @background-change="handleBackgroundChange"
            @preview-toggle="handlePreviewToggle"
          />
        </div>
        
        <!-- 右侧：实时预览 -->
        <div class="compose-main">
          <LivePreview
            v-if="selectedTemplate"
            :template="selectedTemplate"
            :selected-image="selectedImage ?? undefined"
            :text-areas="textAreas"
            :background="background"
            @text-edit="handleTextEdit"
            @text-move="handleTextMove"
            @text-resize="handleTextResize"
            @export-complete="handleExportComplete"
          />
          
          <!-- 空状态 -->
          <div v-else class="empty-preview">
            <el-icon size="64" color="rgba(255,255,255,0.5)"><Grid /></el-icon>
            <h3>选择模板开始创作</h3>
            <p>从左侧选择一个模板来开始您的图文创作之旅</p>
          </div>
        </div>
      </div>
      
      <!-- 导出管理器 -->
      <div v-if="selectedTemplate">
        <ExportManager
          :canvas-element="canvasElement"
          :original-width="selectedTemplate.width"
          :original-height="selectedTemplate.height"
          @export-start="handleExportStart"
          @export-complete="handleExportComplete"
          @export-error="handleExportError"
        />
      </div>
      
      <!-- 快速操作面板 -->
      <div class="quick-actions" v-if="selectedTemplate">
        <div class="actions-header">
          <h3>快速操作</h3>
        </div>
        
        <div class="actions-content">
          <el-button 
            type="success" 
            :icon="Share"
            @click="shareComposition"
          >
            分享作品
          </el-button>
          
          <el-button 
            type="info" 
            :icon="DocumentCopy"
            @click="saveTemplate"
          >
            保存为模板
          </el-button>
          
          <el-button 
            type="warning" 
            :icon="RefreshRight"
            @click="resetComposition"
          >
            重置内容
          </el-button>
        </div>
        
        <!-- 作品信息 -->
        <div class="composition-info">
          <div class="info-item">
            <span class="info-label">画布尺寸:</span>
            <span class="info-value">{{ selectedTemplate.width }}×{{ selectedTemplate.height }}px</span>
          </div>
          <div class="info-item">
            <span class="info-label">模板类型:</span>
            <span class="info-value">{{ getCategoryText(selectedTemplate.category) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">文字区域:</span>
            <span class="info-value">{{ textAreas.length }} 个</span>
          </div>
          <div class="info-item" v-if="selectedImage">
            <span class="info-label">图片:</span>
            <span class="info-value">{{ selectedImage.originalName }}</span>
          </div>
        </div>
      </div>
      
      <!-- 保存模板对话框 -->
      <el-dialog
        v-model="saveTemplateVisible"
        title="保存为模板"
        width="500px"
      >
        <el-form :model="templateForm" label-width="100px">
          <el-form-item label="模板名称" required>
            <el-input 
              v-model="templateForm.name" 
              placeholder="输入模板名称"
            />
          </el-form-item>
          
          <el-form-item label="模板分类">
            <el-select v-model="templateForm.category">
              <el-option label="社交媒体" value="social" />
              <el-option label="电商营销" value="ecommerce" />
              <el-option label="海报宣传" value="poster" />
              <el-option label="故事模板" value="story" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="模板描述">
            <el-input
              v-model="templateForm.description"
              type="textarea"
              :rows="3"
              placeholder="输入模板描述"
            />
          </el-form-item>
          
          <el-form-item label="是否公开">
            <el-switch 
              v-model="templateForm.isPublic"
              active-text="公开"
              inactive-text="私有"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="saveTemplateVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmSaveTemplate"
            :loading="savingTemplate"
          >
            {{ savingTemplate ? '保存中...' : '保存模板' }}
          </el-button>
        </template>
      </el-dialog>
      
      <!-- 分享对话框 -->
      <el-dialog
        v-model="shareVisible"
        title="分享作品"
        width="400px"
      >
        <div class="share-content">
          <div class="share-preview">
            <img v-if="exportedImageUrl" :src="exportedImageUrl" alt="作品预览" />
            <div v-else class="share-placeholder">
              <el-icon size="48"><Picture /></el-icon>
              <p>请先导出作品</p>
            </div>
          </div>
          
          <div class="share-options">
            <el-button 
              type="primary" 
              @click="copyShareLink"
              :icon="Link"
            >
              复制链接
            </el-button>
            <el-button 
              type="success" 
              @click="downloadShare"
              :icon="Download"
            >
              下载图片
            </el-button>
            <el-button 
              type="info" 
              @click="shareToSocial"
              :icon="Share"
            >
              社交分享
            </el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, Share, DocumentCopy, RefreshRight, Grid, Picture, Link
} from '@element-plus/icons-vue'
import PageContainer from '@/components/layout/PageContainer.vue'
import TemplateSelector from '@/components/compose/TemplateSelector.vue'
import ContentEditor from '@/components/compose/ContentEditor.vue'
import LivePreview from '@/components/compose/LivePreview.vue'
import ExportManager from '@/components/compose/ExportManager.vue'
import { imageApi } from '@/api/image'
import { textGenerationApi } from '@/api/ai'
import type { ImageModel, TextContentModel } from '@/types'
import { copyToClipboard } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const selectedTemplate = ref<any>(null)
const selectedImage = ref<ImageModel | null>(null)
const availableImages = ref<ImageModel[]>([])
const textAreas = ref<any[]>([])
const background = ref<any>(null)
const exporting = ref(false)
const exportedImageUrl = ref('')
const canvasElement = ref<HTMLElement | null>(null)

// 对话框状态
const saveTemplateVisible = ref(false)
const shareVisible = ref(false)
const savingTemplate = ref(false)

const templateForm = reactive({
  name: '',
  category: 'social',
  description: '',
  isPublic: false
})

// 方法
const handleSelectTemplate = (template: any) => {
  selectedTemplate.value = template
  
  // 初始化文字区域
  textAreas.value = template.layout.textAreas.map((area: any) => ({
    placeholder: area.placeholder,
    content: '',
    fontSize: parseInt(area.style.fontSize) || 24,
    color: area.style.color || '#000000',
    fontStyles: [],
    textAlign: area.style.textAlign || 'center'
  }))
  
  // 初始化背景
  background.value = {
    type: 'color',
    value: template.backgroundColor
  }
}

const handleCreateTemplate = (template: any) => {
  ElMessage.success('自定义模板创建成功')
}

const handleImageChange = (image: ImageModel) => {
  selectedImage.value = image
}

const handleTextChange = (newTextAreas: any[]) => {
  textAreas.value = newTextAreas
}

const handleStyleChange = () => {
  // 样式变化处理
}

const handleBackgroundChange = (newBackground: any) => {
  background.value = newBackground
}

const handlePreviewToggle = (show: boolean) => {
  // 预览切换处理
}

const handleTextEdit = (index: number, content: string) => {
  if (textAreas.value[index]) {
    textAreas.value[index].content = content
  }
}

const handleTextMove = (index: number, position: any) => {
  if (textAreas.value[index]) {
    textAreas.value[index].position = position
  }
}

const handleTextResize = (index: number, size: any) => {
  if (textAreas.value[index]) {
    textAreas.value[index].size = size
  }
}

const handleExportStart = () => {
  exporting.value = true
}

const handleExportComplete = (result: any) => {
  exportedImageUrl.value = result.dataUrl || result
  exporting.value = false
  ElMessage.success('导出完成')
}

const handleExportError = (error: any) => {
  exporting.value = false
  console.error('导出失败:', error)
  ElMessage.error('导出失败，请重试')
}

const quickExport = () => {
  // 触发预览组件的导出功能
  ElMessage.info('请在预览区域点击导出按钮')
}

const shareComposition = () => {
  if (!exportedImageUrl.value) {
    ElMessage.warning('请先导出作品')
    return
  }
  shareVisible.value = true
}

const saveTemplate = () => {
  if (!selectedTemplate.value) {
    ElMessage.warning('请先选择模板')
    return
  }
  
  templateForm.name = `${selectedTemplate.value.name} - 副本`
  templateForm.category = selectedTemplate.value.category
  templateForm.description = selectedTemplate.value.description
  
  saveTemplateVisible.value = true
}

const resetComposition = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置所有内容吗？此操作不可撤销。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 重置文字内容
    textAreas.value.forEach(area => {
      area.content = ''
    })
    
    // 重置背景
    if (selectedTemplate.value) {
      background.value = {
        type: 'color',
        value: selectedTemplate.value.backgroundColor
      }
    }
    
    ElMessage.success('内容已重置')
  } catch {
    // 用户取消
  }
}

const confirmSaveTemplate = async () => {
  if (!templateForm.name) {
    ElMessage.warning('请输入模板名称')
    return
  }
  
  savingTemplate.value = true
  
  try {
    // 模拟保存模板
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    ElMessage.success('模板保存成功')
    saveTemplateVisible.value = false
    
    // 重置表单
    Object.assign(templateForm, {
      name: '',
      category: 'social',
      description: '',
      isPublic: false
    })
  } catch (error) {
    ElMessage.error('模板保存失败')
  } finally {
    savingTemplate.value = false
  }
}

const copyShareLink = async () => {
  try {
    const shareLink = `${window.location.origin}/compose/share/${Date.now()}`
    await copyToClipboard(shareLink)
    ElMessage.success('分享链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const downloadShare = () => {
  if (exportedImageUrl.value) {
    const link = document.createElement('a')
    link.href = exportedImageUrl.value
    link.download = `图文作品_${Date.now()}.png`
    link.click()
    ElMessage.success('开始下载')
  }
}

const shareToSocial = () => {
  ElMessage.info('社交分享功能开发中...')
}

const loadAvailableImages = async () => {
  try {
    const response = await imageApi.getImages({
      page: 0,
      size: 50,
      sortBy: 'createdAt',
      sortDir: 'desc'
    })
    
    if (response.success && response.data) {
      availableImages.value = response.data
    }
  } catch (error) {
    console.error('加载图片失败:', error)
  }
}

const getCategoryText = (category: string) => {
  switch (category) {
    case 'social': return '社交媒体'
    case 'ecommerce': return '电商营销'
    case 'poster': return '海报宣传'
    case 'story': return '故事模板'
    default: return category
  }
}

// 生命周期
onMounted(async () => {
  await loadAvailableImages()
  
  // 检查路由参数
  const imageId = route.query.imageId
  const textId = route.query.textId
  const expandedIds = route.query.expandedIds
  
  if (imageId) {
    // 从图片ID加载图片
    try {
      const response = await imageApi.getImageById(parseInt(imageId as string))
      if (response.success && response.data) {
        selectedImage.value = response.data
      }
    } catch (error) {
      console.error('加载图片失败:', error)
    }
  }
  
  if (textId) {
    // 从文案ID加载文案内容
    try {
      const response = await textGenerationApi.getTextHistory(parseInt(imageId as string))
      if (response.success && response.data) {
        const textContent = response.data.find((t: TextContentModel) => t.id === parseInt(textId as string))
        if (textContent && textAreas.value.length > 0) {
          textAreas.value[0].content = textContent.content
        }
      }
    } catch (error) {
      console.error('加载文案失败:', error)
    }
  }
})
</script>

<style scoped>
.compose-page {
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
}

.compose-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.page-description {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.compose-content {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 30px;
  margin-bottom: 30px;
}

.compose-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
  position: sticky;
  top: 20px;
  height: fit-content;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.compose-main {
  min-width: 0;
}

.empty-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  color: rgba(255, 255, 255, 0.7);
  text-align: center;
}

.empty-preview h3 {
  margin: 20px 0 10px 0;
  color: white;
}

/* 快速操作面板 */
.quick-actions {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.actions-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.actions-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.actions-content {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.composition-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
}

.info-value {
  font-size: 14px;
  font-weight: 500;
  color: white;
}

/* 分享对话框样式 */
.share-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.share-preview {
  text-align: center;
}

.share-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.share-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 150px;
  background: #f5f5f5;
  border-radius: 8px;
  color: #999;
}

.share-options {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .compose-content {
    grid-template-columns: 350px 1fr;
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .compose-page {
    padding: 15px;
  }
  
  .compose-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .compose-sidebar {
    position: static;
    max-height: none;
  }
  
  .actions-content {
    justify-content: space-between;
  }
  
  .composition-info {
    grid-template-columns: 1fr;
  }
  
  .share-options {
    flex-direction: column;
  }
}
</style>